import tornado.web
import asyncio, json
from core.base_tornado_request_handler import BaseTornadoRequestHandler
from db import RolesDB

class ApiRoleHandler(BaseTornadoRequestHandler):
  async def get(self, action):
    if action == "list":
      await self.get_list()
  
  async def post(self, action):
    if action == "upload":
      await self.upload_role_file()
      return
    if action == "clear":
      await self.clear_role()
      return
    if action == "delete":
      await self.delete_role()
      return
    if action == "update":
      await self.update_role()

  async def get_list(self):
    role_list = await RolesDB.all()
    self.return_json({"list": [role.to_dict() for role in role_list]})

  async def update_role(self):
    data = json.loads(self.request.body) if self.request.body else {}
    role_id = data.get("id", 0)
    if role_id == 0:
      role = await RolesDB.create(**data)
      self.return_json({"role": role.to_dict()})
      return
    filter_role = await RolesDB.filter(id=role_id).get_or_none()
    if filter_role is None:
      self.return_json(data=None, code=403, status=False, message="角色不存在")
      return
    # normal_data = {k: v for k, v in data.items() if k != "id"}
    filter_role.update_from_dict(data)
    await filter_role.save()
    self.return_json({"role": filter_role.to_dict()})

  async def clear_role(self):
    num = await RolesDB.all().delete()
    self.return_json({"num": num})

  async def delete_role(self):
    data = json.loads(self.request.body) if self.request.body else {}
    role_id = data.get("id", 0)
    num = await RolesDB.filter(id=role_id).delete()
    self.return_json({"num": num})
  
  async def upload_role_file(self):
    files = self.request.files.get("file", None)
    if not files or len(files) == 0:
      self.return_json(data=None, code=500, status=False, message="未找到文件")
      return
    file_body = files[0]["body"]
    file_name = files[0]['filename']
    if not file_name.endswith('.json'):
      self.return_json(data=None, code=500, status=False, message="请上传JSON格式的文件")
      return
    json_data = None
    try:
      # 尝试解析 JSON 数据
      json_data = json.loads(file_body.decode('utf-8'))
    except json.JSONDecodeError:
      pass
    if json_data is None:
      self.return_json(data=None, code=500, status=False, message="无法解析JSON文件")
      return
    role_list = json_data.get("role_list", [])
    db_role_list = [RolesDB(craft_type=x.get("craft_type"), role_name=x.get("role_name"), realm_name=x.get("realm_name")) for x in role_list]
    await RolesDB.bulk_create(db_role_list)
    self.return_json(data=json_data)
  